
import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { NzMessageService, UploadFile, NzModalService, NzNotificationService } from 'ng-zorro-antd';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { ActivatedRoute, Router } from '@angular/router';
import {SettingsService, TitleService} from '@delon/theme';
import { ProductService } from '../../../../service/prod/product.service';
import { EmitterService } from 'app/service/emit.service';
import { CommService } from '../../../../service/comm/comm.service';
import { ServiceResult, Constant } from '@core/constant';
import { ProductSkuEditV2Component } from '@shared/component/product-sku-edit-v2/product-sku-edit-v2.component';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {Timeout} from "@shared/descriptor/timeout";

@Component({
  selector: 'csList-addone',
  templateUrl: './csList-addone.component.html',
  styleUrls: ['./csList-addone.component.less']
})
export class csListAddoneComponent implements OnInit, OnDestroy {
  orderNo = null;

  private sub: any;

  product:  any = {
    // orderAmount:null,
    // orderPeriod:null,
    // orderNo:null,
    // proNo: '' /*No show*/,
    // cusName: null,
    // cusMobile: null,
    // cusrIdtype: null,
    // cusIncard: null /*No show*/,
    // cusIdValidfrom: null /*No show*/,
    // cusIdValidto: null /*No show*/,
    // cusResAddr: null,
    // cusGender: '男',
    // cusMaritalStatus: null /*No show*/,
    // cusDeu: null /*No show*/,
    // cusEthnical: null,
    // cusAge: null,
    // cusBirthday: null,
    // cusQqid: null /*No show*/,
    // cusRemark: null,
    bmDate: null,
    bmTime: null,
    bxRq: null,
    carColor: null,
    carDetail: null,
    carVin: null,
    conJson: null,
    conNo: null,
    conType: null,
    conUrl: null,
    createSysorg: null,
    createUser: null,
    cusAge: null,
    cusBirthday: null,
    cusDeu: null,
    cusEthnical: null,
    cusGender: null,
    cusIdValidfrom: null,
    cusIdValidto: null,
    cusIncard: null,
    cusMaritalStatus: null,
    cusMobile: null,
    cusName: null,
    cusQqid: null,
    cusRemark: null,
    cusResAddr: null,
    cusWechatid: null,
    cusrIdtype: null,
    danganNo: null,
    diyaStatus: null,
    diyaUser: null,
    fangkBank: null,
    fangkId: null,
    fangkName: null,
    fangkType: null,
    fkAmount: null,
    gpsInsAddr: null,
    gpsInsData: null,
    gpsInsMobile: null,
    gpsInsUser: null,
    gpsStatus: null,
    gpsUser: null,
    guohuStatus: null,
    guohuUser: null,
        luqiaoRq: null,
       lxMobile1: null,
       lxMobile2: null,
       lxMobile3: null,
       lxName1: null,
       lxName2: null,
       lxName3: null,
       mpName: null,
       mpUrl: null,
       mpbackUrl: null,
       nianjiaRq: null,
       orderAmount: null,
       orderArea: null,
       orderBy1: null,
       orderBy10: null,
       orderBy11: null,
       orderBy12: null,
       orderBy13: null,
       orderBy14: null,
       orderBy15: null,
       orderBy16: null,
       orderBy17: null,
       orderBy18: null,
       orderBy2: null,
       orderBy3: null,
       orderBy4: null,
       orderBy5: null,
       orderBy6: null,
       orderBy7: null,
       orderBy8: null,
       orderBy9: null,
       orderCarno: null,
       orderCartype: null,
       orderInfo: null,
       orderNo: null,
       orderOper: null,
       orderPeriod: null,
       orderStatus: null,
       proClass: null,
       proIsdb: null,
       proName: null,
       proNo: null,
       proType: null,
       proWf: null,
       qiandanUser: null,
       sfAnpaijiafang: null,
       sfDianshen: null,
       wbName: null,
       wbUrl: null,
       wbbackUrl: null,
       yinhangUser: null,

    dypname: [null],
    dypvalue: [null],
    dypyear: [null],
    dyptype: [null],
    dypclass: [null],

    dypremark1: [null],
    dypremark2: [null],
    dypremark3: [null]
  };

  // 预览图片对象
  previewImage = '';
  // 是否可以预览
  previewVisible = false;
  profileForm: FormGroup;

  saleing = false;
  proNos = [];
  cusrIdtypes = [];
  cusGenders = [];
  cusMaritalStatuss = [];
  cusDeus = [];
  cusEthnicals = [];
  bpmStatus = [];
  dyptypes = [];
  dypclasss = [];
  relTypes=[];
  avatarUrl1:string;
  avatarUrl2:string;

  avatarUrl3:string;

  avatarUrl4:string;
  avatarUrl5:string;
  loading = false;
  uploadUrl = '';
  uploadUr5 = '';

  avatarParam1 = { sbtype: '2', filetype:'sb',orderNo: this.orderNo};
  avatarParam2 = { sbtype: '3', filetype:'sb', orderNo: this.orderNo};
  avatarParam3 = { sbtype: '6',  filetype:'sb',orderNo: this.orderNo};
  avatarParam4 = { sbtype: '2', filetype:'sb', orderNo: this.orderNo};
  avatarParam5 = { sbtype: 'No',  filetype:'jj',orderNo: this.orderNo};

  fileList = [ ];


  constructor(
    fb: FormBuilder,
    public setting: SettingsService,
    private msg: NzMessageService,
    private modalService: NzModalService,
    private productService: ProductService,
    private emit: EmitterService,
    private notification: NzNotificationService,
    private route: ActivatedRoute,
    private titleService: TitleService,
    private router: Router,
    private cnt: Constant,
    private comm: CommService
  )
    {
      this.titleService.setTitle("添加订单");

    }


  ngOnInit(): void {
    this.loadproNos();
    this.loadcusrIdtypes();
    this.loadcusGenders();
    this.loadcusMaritalStatuss();
    this.loadcusDeus();
    this.loadcusEthnicals();
    this.loadbpmStatus();
    this.loaddyptypes();
    this.loaddypclasss();
    this.loadrelTypes();
    this.uploadUrl = this.productService.uploadsbUrl();
    this.uploadUr5 = this.productService.uploadUrl();
    // this.orderNo = this.comm.getnectno("order");
    // 获取参数
    this.sub = this.route.params.subscribe(params => {
      this.product.id = params["id"];
      // 获取商品详情
    });
    this.comm.getno("order").pipe().subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      this.orderNo =  ret['data'];
      this.product.orderNo =  ret['data'];
      console.log("datacezorderNo"+this.orderNo);
      this.avatarParam1 = { sbtype: '2', filetype:'sb',orderNo: this.orderNo};
      this.avatarParam2 = { sbtype: '3', filetype:'sb', orderNo: this.orderNo};
      this.avatarParam3 = { sbtype: '6',  filetype:'sb',orderNo: this.orderNo};
      this.avatarParam4 = { sbtype: '2', filetype:'sb', orderNo: this.orderNo};
      this.avatarParam5 = { sbtype: 'No',  filetype:'jj',orderNo: this.orderNo};
    });
    this.product.cusrIdtype='10';
    this.titleService.setTitle("添加订单");
    setTimeout(() => {
      this.emit.sendMessage("HIDE_REUSE_TAB");
    }, 10);

  }
  ngOnDestroy() {
    this.emit.sendMessage("SHOW_REUSE_TAB");
  }
  // 加载产品
  loadproNos() {
    this.proNos = [];
    this.comm.getType("proNo").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
        for (const row of ret['data']) {
              this.proNos.push({ text: row.typename, value: row.typecode });
          }
      }
    })
  }

  // 加载证件类型
  loadcusrIdtypes() {
    this.cusrIdtypes = [];
    this.comm.getType("idType").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
          for (const row of ret['data']) {
              this.cusrIdtypes.push({ text: row.typename, value: row.typecode });
          }
      }
    })
  }

  // 加载性别
  loadcusGenders() {
    this.cusGenders = [];
    this.comm.getType("sex").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
          for (const row of ret['data']) {
              this.cusGenders.push({ text: row.typename, value: row.typecode });
          }
      }
    })
  }

  // 加载婚姻
  loadcusMaritalStatuss() {
    this.cusMaritalStatuss = [];
    this.comm.getType("marType").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
          for (const row of ret['data']) {
              this.cusMaritalStatuss.push({ text: row.typename, value: row.typecode });
          }
      }
    })
  }

  // 加载学历
  loadcusDeus() {
    this.cusDeus = [];
    this.comm.getType("eduType").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
          for (const row of ret['data']) {
              this.cusDeus.push({ text: row.typename, value: row.typecode });
          }
      }
    })
  }
//加载民族
  loadcusEthnicals() {
    this.cusEthnicals = [];
    this.comm.getType("ethType").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
          for (const row of ret['data']) {
              this.cusEthnicals.push({ text: row.typename, value: row.typecode });
          }
      }
    })
  }
  // 加载证件类型
  loadbpmStatus() {
    this.bpmStatus = [];
    this.comm.getType("bpm_status").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
        for (const row of ret['data']) {
          this.bpmStatus.push({ text: row.typename, value: row.typecode });
        }
      }
    })
  }
  // 加载证件类型
  loaddyptypes() {
    this.dyptypes = [];
    this.comm.getType("dyptype").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
        for (const row of ret['data']) {
          this.dyptypes.push({ text: row.typename, value: row.typecode });
        }
      }
    })
  }
  loaddypclasss() {
    this.dypclasss = [];
    this.comm.getType("dypclass").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
        for (const row of ret['data']) {
          this.dypclasss.push({ text: row.typename, value: row.typecode });
        }
      }
    })
  }
  loadrelTypes() {
    this.relTypes = [];
    this.comm.getType("reltype").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
        for (const row of ret['data']) {
          this.relTypes.push({ text: row.typename, value: row.typecode });
        }
      }
    })
  }

  @Timeout(500)
  gotoImg() {
    console.log("+this.orderno"+this.orderNo);
    this.router.navigate(['/prod/product/upload/']);
  }

  reset(i) {

  }

  save(bpmStatus) {

    if(this.product.proNo===''){
      this.msg.warning("请选择产品信息");
      return;
    }

    let fxjOrderLoanList = [];
    if(this.product.dypname!=''){
      console.log("this.product.dypname*********"+this.product.dypname);

      let dto ={
        elementNo:10,
        elementName:"抵押品名称",
        elementContent:this.product.dypname
      }
      fxjOrderLoanList.push(dto);
    }

    if(this.product.dypvalue!=''){
      console.log("this.product.dypvalue*********"+this.product.dypvalue);

      let dto ={
        elementNo:20,
        elementName:"抵押品价值",
        elementContent:this.product.dypvalue
      }
      fxjOrderLoanList.push(dto);
    }
    if(this.product.dypyear!=''){
      let dto ={
        elementNo:30,
        elementName:"抵押品年份",
        elementContent:this.product.dypyear
      }
      fxjOrderLoanList.push(dto);
    }

    if(this.product.dyptype!=''){
      let dto ={
        elementNo:40,
        elementName:"抵押品类型",
        elementContent:this.product.dyptype
      }
      fxjOrderLoanList.push(dto);
    }
    if(this.product.dypclass!=''){
      let dto ={
        elementNo:50,
        elementName:"抵押品性质",
        elementContent:this.product.dypclass
      }
      fxjOrderLoanList.push(dto);
    }
    if(this.product.dypremark1!=''){
      let dto ={
        elementNo:60,
        elementName:"抵押品备注1",
        elementContent:this.product.dypremark1
      }
      fxjOrderLoanList.push(dto);
    }
    if(this.product.dypremark2!=''){
      let dto ={
        elementNo:70,
        elementName:"抵押品备注2",
        elementContent:this.product.dypremark2
      }
      fxjOrderLoanList.push(dto);
    }
    if(this.product.dypremark3!='') {
      let dto = {
        elementNo: 80,
        elementName: "抵押品备注3",
        elementContent: this.product.dypremark3

      }

      fxjOrderLoanList.push( dto);

    }
    let fxjOrderEmerList =[];



   var  emergencyContact = this.product.emergencyContact;

    var   emergencyRelation =this.product.emergencyRelation;

    var   emergencyMobile =this.product.emergencyMobile;

    var  emergencyOffice =this.product.emergencyOffice;
    var  emergencyResAddr =this.product.emergencyResAddr;


    //紧急联系人列表
    if(this.product.emergencyRelation!='') {
      let dto = {
        emergencyRelation:  emergencyRelation,//关系
        emergencyContact: emergencyContact,//姓名
        emergencyMobile: emergencyMobile,//电话
        emergencyOffice:emergencyOffice,
        emergencyResAddr:emergencyResAddr//地址
      }
      fxjOrderEmerList.push( dto);

    }

    let fxjOrderMainPage = {
      bpmStatus:bpmStatus,
      createBy:this.setting.user.username,
      sysOrgCode:this.setting.user.sysorgCode,

      orderNo:this.product.orderNo,//订单编号
      bmDate: this.product.bmDate,
      bmTime: this.product.bmTime,
      bxRq: this.product.bxRq,
      carColor: this.product.carColor,
      carDetail: this.product.carDetail,
      carVin: this.product.carVin,
      conJson: this.product.conJson,
      conNo: this.product.conNo,
      conType: this.product.conType,
      conUrl: this.product.conUrl,
      createSysorg: this.product.createSysorg,
      createUser: this.product.createUser,
      cusAge: this.product.cusAge,
      cusBirthday: this.product.cusBirthday,
      cusDeu: this.product.cusDeu,
      cusEthnical: this.product.cusEthnical,
      cusGender: this.product.cusGender,
      cusIdValidfrom: this.product.cusIdValidfrom,
      cusIdValidto: this.product.cusIdValidto,
      cusIncard: this.product.cusIncard,
      cusMaritalStatus: this.product.cusMaritalStatus,
      cusMobile: this.product.cusMobile,
      cusName: this.product.cusName,
      cusQqid: this.product.cusQqid,
      cusRemark: this.product.cusRemark,
      cusResAddr: this.product.cusResAddr,
      cusWechatid: this.product.cusWechatid,
      cusrIdtype: this.product.cusrIdtype,
      danganNo: this.product.danganNo,
      diyaStatus: this.product.diyaStatus,
      diyaUser: this.product.diyaUser,
      fangkBank: this.product.fangkBank,
      fangkId: this.product.fangkId,
      fangkName: this.product.fangkName,
      fangkType: this.product.fangkType,
      fkAmount: this.product.fkAmount,
      gpsInsAddr: this.product.gpsInsAddr,
      gpsInsData: this.product.gpsInsData,
      gpsInsMobile: this.product.gpsInsMobile,
      gpsInsUser: this.product.gpsInsUser,
      gpsStatus: this.product.gpsStatus,
      gpsUser: this.product.gpsUser,
      guohuStatus: this.product.guohuStatus,
      guohuUser: this.product.guohuUser,
      luqiaoRq: this.product.luqiaoRq,
      lxMobile1: this.product.lxMobile1,
      lxMobile2: this.product.lxMobile2,
      lxMobile3: this.product.lxMobile3,
      lxName1: this.product.lxName1,
      lxName2: this.product.lxName2,
      lxName3: this.product.lxName3,
      mpName: this.product.mpName,
      mpUrl: this.product.mpUrl,
      mpbackUrl: this.product.mpbackUrl,
      nianjiaRq: this.product.nianjiaRq,
      orderAmount: this.product.orderAmount,
      orderArea: this.product.orderArea,
      orderBy1: this.product.orderBy1,
      orderBy10: this.product.orderBy10,
      orderBy11: this.product.orderBy11,
      orderBy12: this.product.orderBy12,
      orderBy13: this.product.orderBy13,
      orderBy14: this.product.orderBy14,
      orderBy15: this.product.orderBy15,
      orderBy16: this.product.orderBy16,
      orderBy17: this.product.orderBy17,
      orderBy18: this.product.orderBy18,
      orderBy2: this.product.orderBy2,
      orderBy3: this.product.orderBy3,
      orderBy4: this.product.orderBy4,
      orderBy5: this.product.orderBy5,
      orderBy6: this.product.orderBy6,
      orderBy7: this.product.orderBy7,
      orderBy8: this.product.orderBy8,
      orderBy9: this.product.orderBy9,
      orderCarno: this.product.orderCarno,
      orderCartype: this.product.orderCartype,
      orderInfo: this.product.orderInfo,
      orderOper: this.product.orderOper,
      orderPeriod: this.product.orderPeriod,
      orderStatus: this.product.orderStatus,
      proClass: this.product.proClass,
      proIsdb: this.product.proIsdb,
      proName: this.product.proName,
      proNo: this.product.proNo,
      proType: this.product.proType,
      proWf: this.product.proWf,
      qiandanUser: this.product.qiandanUser,
      sfAnpaijiafang: this.product.sfAnpaijiafang,
      sfDianshen: this.product.sfDianshen,
      wbName: this.product.wbName,
      wbUrl: this.product.wbUrl,
      wbbackUrl: this.product.wbbackUrl,
      yinhangUser: this.product.yinhangUser,



      fxjOrderLoanList:JSON.parse(JSON.stringify(fxjOrderLoanList)),
      fxjOrderEmerList:JSON.parse(JSON.stringify(fxjOrderEmerList)),//紧急联系人

    };

    console.log("fxjOrderMainPage************"+JSON.stringify(fxjOrderMainPage));


    this.loading = true;
    this.productService.addPro(fxjOrderMainPage).pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      this.loading = false;
      if (data.ok === true) {

        this.back();
          this.msg.success("添加成功");
          this.emit.sendMessage("RELOAD_GOODS_LIST");
           } else {
        this.msg.error(data.respMsg);
      }
    })
  }

  back() {
    this.router.navigate(['/prod/product/']);
  }

  beforeUpload = (file: File) => {
    const isJPG = file.type === 'image/jpeg';
    const isPNG = file.type === 'image/png';
    if (!isJPG && !isPNG) {
      this.msg.warning(`No support: ${file.type}`);
    }
    const isLt2M = file.size / 1024 / 1024 < 10;
    if (!isLt2M) {
      this.msg.warning('The pic file not more than 2MB!');
    }
    return (isJPG || isPNG) && isLt2M;
  }

  private getBase64(img: File, callback: (img: any) => void) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

  handleChange1(info: { file: UploadFile }) {


    if (info.file.status === 'uploading') {
      this.loading = true;
      return;
    }
    if (info.file.status === 'done') {
      this.getBase64(info.file.originFileObj, (img: any) => {
        this.loading = false;
        this.avatarUrl1 = img;
        console.log("info1*********"+JSON.stringify(info.file.response[0].piccontent));

        var sfxx=JSON.parse(info.file.response[0].piccontent)

        this.product.cusName=sfxx.result.cardsinfo[0].items[1].content;
        this.product.cusGender=sfxx.result.cardsinfo[0].items[2].content;
        this.product.cusEthnical=sfxx.result.cardsinfo[0].items[3].content;
        this.product.cusBirthday=sfxx.result.cardsinfo[0].items[4].content;
        this.product.cusResAddr=sfxx.result.cardsinfo[0].items[5].content;
        this.product.cusIncard=sfxx.result.cardsinfo[0].items[6].content;
        info.file=null;
      });
    }
    if (info.file.status === 'error') {
      this.msg.error(info.file.error.error);
    }
  }
  handleChange2(info: { file: UploadFile }) {
    if (info.file.status === 'uploading') {
      this.loading = true;
      return;
    }


    if (info.file.status === 'done') {
      this.getBase64(info.file.originFileObj, (img: any) => {
        this.loading = false;
        this.avatarUrl2 = img;


        var sfxx=JSON.parse(info.file.response[0].piccontent)

        console.log("varfrom*********"+JSON.stringify(sfxx));
        this.product.cusIdValidfrom= sfxx.result.cardsinfo[0].items[3].content;
        this.product.cusIdValidto=sfxx.result.cardsinfo[0].items[4].content;

      });
    }
    if (info.file.status === 'error') {
      this.msg.error(info.file.error.error);
    }
  }
  handleChange3(info: { file: UploadFile }) {
    if (info.file.status === 'uploading') {
      this.loading = true;
      return;
    }
    if (info.file.status === 'done') {
      this.getBase64(info.file.originFileObj, (img: any) => {
        this.loading = false;
        this.avatarUrl3 = img;

        var sfxx=JSON.parse(info.file.response[0].piccontent)

        this.product.dypname= sfxx.result.cardsinfo[0].items[5].content +"/"+  sfxx.result.cardsinfo[0].items[2].content;

        this.product.dypvalue = sfxx.result.cardsinfo[0].items[1].content;
        this.product.dypyear = sfxx.result.cardsinfo[0].items[3].content;
        this.product.dyptype  =  sfxx.result.cardsinfo[0].items[8].content + "/"+sfxx.result.cardsinfo[0].items[9].content;

        this.product.dypclass =  sfxx.result.cardsinfo[0].items[10].content;

        this.product.dypremark1 = sfxx.result.cardsinfo[0].items[4].content;
        this.product.dypremark2 = sfxx.result.cardsinfo[0].items[6].content;
        this.product.dypremark3   = sfxx.result.cardsinfo[0].items[7].content;

      });
    }
    if (info.file.status === 'error') {
      this.msg.error(info.file.error.error);
    }
  }
  handleChange4(info: { file: UploadFile }) {
    if (info.file.status === 'uploading') {
      this.loading = true;
      return;
    }
    if (info.file.status === 'done') {
      this.getBase64(info.file.originFileObj, (img: any) => {
        this.loading = false;
        this.avatarUrl4 = img;
        var sfxx=JSON.parse(info.file.response[0].piccontent)

        console.log("varfrom*********"+JSON.stringify(sfxx));
        this.product.emergencyContact=sfxx.result.cardsinfo[0].items[1].content;

        this.product.emergencyResAddr=sfxx.result.cardsinfo[0].items[5].content;
        this.product.emergencyOffice=sfxx.result.cardsinfo[0].items[6].content;

      });
    }
    if (info.file.status === 'error') {
      this.msg.error(info.file.error.error);
    }
  }
  handleChange5(info: { file: UploadFile }) {
    if (info.file.status === 'uploading') {
      this.loading = true;
      return;
    }
    if (info.file.status === 'done') {
      this.getBase64(info.file.originFileObj, (img: any) => {
        this.loading = false;
        this.avatarUrl5 = img;

      });
    }
    if (info.file.status === 'error') {
      this.msg.error(info.file.error.error);
    }
  }

  handlePreview = (file: UploadFile) => {
    this.previewImage = file.url || file.thumbUrl;
    this.previewVisible = true;
  }
}
